from uuid import UUID, uuid4

from PyQt5.QtWidgets import QVBoxLayout, QWidget, QPushButton, QTreeView, QAbstractItemView
from PyQt5.QtCore import Qt, QModelIndex
from PyQt5.QtGui import QStandardItemModel

from protolib.gui_utils.pyqt5_messageboxes import show_question_messagebox

from data import database

from player.dialogs.editors.artist import ArtistEditor

class ArtistList(QWidget):
    ARTIST_NAME, ARTIST_UUID = range(2)

    def __init__(self):
        super().__init__(None)

        layout = QVBoxLayout()

        self.artist_list = QTreeView()
        self.artist_list.doubleClicked.connect(self.artist_list_double_clicked)
        self.artist_list.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.artist_list_model = QStandardItemModel(0, 2, self)
        self.artist_list.setModel(self.artist_list_model)
        self.artist_list_model.setHeaderData(self.ARTIST_NAME, Qt.Horizontal, "Name")
        self.artist_list_model.setHeaderData(self.ARTIST_UUID, Qt.Horizontal, "UUID")
        layout.addWidget(self.artist_list)
        self.refresh_artist_list()

        self.create_artist_button = QPushButton('Create Artist')
        self.create_artist_button.clicked.connect(self.create_artist)
        layout.addWidget(self.create_artist_button)

        self.delete_artist_button = QPushButton('Delete Artist')
        self.delete_artist_button.clicked.connect(self.delete_artist)
        layout.addWidget(self.delete_artist_button)

        self.setLayout(layout)

    def refresh_artist_list(self):
        self.artist_list_model.removeRows(0, self.artist_list_model.rowCount())
        for uuid in sorted(database['artists'], key=lambda x: str(database['artists'][x]['name']) if database['artists'][x]['name'] else 'No Name', reverse=True):
            self.artist_list_model.insertRow(0)
            self.artist_list_model.setData(self.artist_list_model.index(0, self.ARTIST_NAME), database['artists'][uuid]['name'] if database['artists'][uuid]['name'] else 'No Name')
            self.artist_list_model.setData(self.artist_list_model.index(0, self.ARTIST_UUID), str(uuid))

        self.artist_list.resizeColumnToContents(self.ARTIST_NAME)
        self.artist_list.resizeColumnToContents(self.ARTIST_UUID)

    def uuid_from_index(self, index: QModelIndex) -> UUID:
        index = self.artist_list_model.index(index.row(), self.ARTIST_UUID)
        item = self.artist_list_model.itemFromIndex(index)
        uuid = item.text()
        return UUID(uuid)

    def artist_list_double_clicked(self, index: QModelIndex):
        uuid = self.uuid_from_index(index)
        editor = ArtistEditor(uuid)
        editor.exec_()
        self.refresh_artist_list()

    def create_artist(self):
        uuid = uuid4()
        artist = {
            'name': 'New Artist'
        }
        database['artists'][uuid] = artist
        editor = ArtistEditor(uuid)
        editor.exec_()
        self.refresh_artist_list()

    def delete_artist(self):
        if not show_question_messagebox('Are you sure?', 'You are about to permanently delete an artist. All tracks associated with this artist will have this artist removed from there associations. This action cannot be undone.'):
            return
        index = self.artist_list.selectedIndexes()[0]
        uuid = self.uuid_from_index(index)
        for track_uuid in database['music']:
            if uuid in database['music'][track_uuid]['artists']:
                database['music'][track_uuid]['artists'].remove(uuid)
        del database['artists'][uuid]
        self.refresh_artist_list()
